package SuperMarketGuis;

import java.sql.*;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;


public class StoreManagement extends javax.swing.JDialog {
    
    private static Connection conn = null;
    private static Statement stmt = null;
    private static String dbURL = 
	"jdbc:derby://localhost:1527/SuperMarket;create=true;user=plh24;password=plh24";
    
    
    private void Addstore(String sn, String sa)
    {
                if ((sn.equalsIgnoreCase(""))||(sa.equalsIgnoreCase("")))
                {
                    MessageArea.setText("Πρέπει να δώσετε έγκαιρα στοιχεία για το κατάστημα.");
                }
                else
                    {
                        try
                        {
                            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
                            //Get a connection
                            conn = DriverManager.getConnection(dbURL); 
                            stmt = conn.createStatement();
                            String query = ("SELECT * FROM store where name like '"
                            +sn+"' and address like '"+sa+"'");
                            ResultSet rst1 = stmt.executeQuery(query);
                            if (rst1.next()) 
                                {
                                    MessageArea.setText("Το κατάστημα "
                                            +sn+" με διεύθυνση "+sa+" υπάρχει ήδη.");
                                }
                            else
                            {
                                query = ("INSERT INTO store (name,address) VALUES ('"
                                        +sn+"','"+sa+"')");
                                int i = stmt.executeUpdate(query);
                                MessageArea.setText("Το κατάστημα "+sn+" με διεύθυνση "
                                        +sa+" καταχωρήθηκε επιτυχώς.");
                            }
                            // Disconnect from database
                            stmt.close();
                            conn.close();
                        }
                        catch (Exception ex)
                        {
                            MessageArea.setText(ex.getMessage());
                        }
                }
    }
    
    private void EditStore(int storeid, String storename, String storeaddress)
    {
        if ((storename.trim().equalsIgnoreCase(""))||(storeaddress.trim().equalsIgnoreCase("")))
                {
                    MessageArea.setText("Πρέπει να δώσετε έγκαιρα στοιχεία για το κατάστημα.");
                }
                else
                {
                    try
                    {   
                        Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
                        conn = DriverManager.getConnection(dbURL);
                        stmt = conn.createStatement();
                        String sqlquery1 = ("Select * from plh24.store where name like '"
                                +storename+"' and address like '"+storeaddress+"'");
                        ResultSet res1 = stmt.executeQuery(sqlquery1);
            
                        if (res1.next())
                            {
                                MessageArea.setText("Το κατάστημα "+storename+" με διεύθυνση "
                                        +storeaddress+" υπάρχει ήδη.");
                            }
                        else
                            {
                                String sqlquery2 = ("Update plh24.store set name = '"
                                        +storename+"',address = '"+storeaddress+"' where store_id ="+storeid);
                                int rowaffected = stmt.executeUpdate(sqlquery2);
                            }
                        stmt.close();
                        conn.close();
                    }
                    catch(Exception ex)
                        {
                            System.out.println(ex.getMessage());
                        }
                }
    }
    
    private void DeleteStore(int storeid)
        {
                    try
                    {   
                        Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
                        conn = DriverManager.getConnection(dbURL);
                        stmt = conn.createStatement();
                        String sqlquery = ("Delete from plh24.store where store_id = "+storeid);
                        int rowaffected = stmt.executeUpdate(sqlquery);
                        stmt.close();
                        conn.close();
                    }
                    catch(Exception ex)
                        {
                            System.out.println(ex.getMessage());
                        }
        }
    
    private void initTable()
    {
        try
        {   
            conn = DriverManager.getConnection(dbURL);
            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("Select store_id,name,address from plh24.store order by name");
            ResultSetMetaData rsmt = rs.getMetaData();
            int column = rsmt.getColumnCount();
            
            DefaultTableModel dtm = new DefaultTableModel();
            Vector clabel = new Vector();
            Vector data_row = new Vector();
            for (int i=1;i<=column;i++)
            {
                clabel.addElement(rsmt.getColumnName(i));
                dtm.setColumnIdentifiers(clabel);}
            while (rs.next())
                    {
                    data_row = new Vector();
                    for (int j=1;j<=column;j++)
                        {
                            data_row.addElement(rs.getString(j));
                        }
                    dtm.addRow(data_row);
                    StoreList.setModel(dtm);
                    }
            
            stmt.close();
            conn.close();
        }
        catch(Exception ex){System.out.println(ex.getMessage());}
    }
    
    
    
    // jdbc Connection
    

    public StoreManagement(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        initTable();
        
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        StoreList = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        StoreName = new javax.swing.JTextField();
        StoreAddress = new javax.swing.JTextField();
        bAddStore = new javax.swing.JButton();
        bStoreUpdate = new javax.swing.JButton();
        bStoreDelete = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        MessageArea = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        bReturn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setAlwaysOnTop(true);

        jLabel1.setFont(new java.awt.Font("Calibri", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Διαχείρηση Καταστημάτων");

        jScrollPane1.setViewportBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(0, 0, 255)));

        StoreList.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.ABOVE_TOP, new java.awt.Font("Calibri", 1, 18))); // NOI18N
        StoreList.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
        StoreList.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STORE_ID", "NAME", "ADDRESS"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(StoreList);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
        jLabel2.setText("Όνομα Καταστήματος:");

        jLabel3.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
        jLabel3.setText("Διεύθυνση Καταστήματος:");

        StoreName.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N

        StoreAddress.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N

        bAddStore.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        bAddStore.setText("Προσθήκη");
        bAddStore.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAddStoreActionPerformed(evt);
            }
        });

        bStoreUpdate.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        bStoreUpdate.setText("Τροποποίηση");
        bStoreUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bStoreUpdateActionPerformed(evt);
            }
        });

        bStoreDelete.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        bStoreDelete.setText("Διαγραφή");
        bStoreDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bStoreDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(34, 34, 34)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(StoreName)
                    .addComponent(StoreAddress))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(60, 60, 60)
                .addComponent(bAddStore)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 161, Short.MAX_VALUE)
                .addComponent(bStoreUpdate)
                .addGap(143, 143, 143)
                .addComponent(bStoreDelete)
                .addGap(67, 67, 67))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(StoreName, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(StoreAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE))
                .addGap(26, 26, 26)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bAddStore)
                    .addComponent(bStoreUpdate)
                    .addComponent(bStoreDelete))
                .addContainerGap(25, Short.MAX_VALUE))
        );

        MessageArea.setEditable(false);
        MessageArea.setColumns(1);
        MessageArea.setFont(new java.awt.Font("Calibri", 1, 18)); // NOI18N
        MessageArea.setForeground(new java.awt.Color(204, 0, 0));
        MessageArea.setLineWrap(true);
        MessageArea.setRows(5);
        MessageArea.setText("1)    Για να προσθέσετε κατάστημα καταχωρήστε το όνομα και τη διεύθυνση στα αντίστοιχα              πεδία και πατήστε το κουμπί \"Προσθήκη\".\n2)    Για να τροποποιήσετε ένα υπάρχον κατάστημα επιλέξτε το από τον πίνακα, δώστε το νέο            όνομα και διεύθυνση στα αντίστοιχα πεδία και πατήστε το κουμπί \"Τροποποίηση\".\n3)    Για να διαγράψετε ένα υπάρχον κατάστημα επιλέξτε το από τον πίνακα και πατήστε το                κουμπί \"Διαγραφή\".\n");
        MessageArea.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(0, 255, 255), null));
        MessageArea.setSelectedTextColor(new java.awt.Color(204, 0, 0));
        jScrollPane2.setViewportView(MessageArea);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 38, Short.MAX_VALUE)
        );

        bReturn.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        bReturn.setText("Επιστροφή");
        bReturn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bReturnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(336, 336, 336)
                .addComponent(bReturn)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(17, 17, 17)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(bReturn)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bAddStoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAddStoreActionPerformed
           Addstore(StoreName.getText(),StoreAddress.getText());
           initTable();
    }//GEN-LAST:event_bAddStoreActionPerformed

    private void bStoreUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bStoreUpdateActionPerformed
            
            int k=-1;
            k = StoreList.getSelectedRow();
            if (k==-1)
            {
                MessageArea.setText("Πρέπει να επιλέξετε ένα κατάστημα από τη λίστα.");
            }
            else
            {
                EditStore(Integer.parseInt(StoreList.getValueAt(k, 0).toString()), StoreName.getText(), StoreAddress.getText());
                //this.dispose();
                initTable();
            }
    }//GEN-LAST:event_bStoreUpdateActionPerformed

    private void bReturnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bReturnActionPerformed
            this.dispose();
    }//GEN-LAST:event_bReturnActionPerformed

    private void bStoreDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bStoreDeleteActionPerformed
            int k=-1,storeid;
            k = StoreList.getSelectedRow();
            if (k==-1)
            {
                MessageArea.setText("Πρέπει να επιλέξετε ένα κατάστημα από τη λίστα.");
            }
            else
            {
                DeleteStore(Integer.parseInt(StoreList.getValueAt(k, 0).toString()));
                this.dispose();
            }
    }//GEN-LAST:event_bStoreDeleteActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(StoreManagement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StoreManagement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StoreManagement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StoreManagement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                StoreManagement dialog = new StoreManagement(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea MessageArea;
    private javax.swing.JTextField StoreAddress;
    private javax.swing.JTable StoreList;
    private javax.swing.JTextField StoreName;
    private javax.swing.JButton bAddStore;
    private javax.swing.JButton bReturn;
    private javax.swing.JButton bStoreDelete;
    private javax.swing.JButton bStoreUpdate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
